package com.ambow.store.controller;

import com.ambow.store.controller.Exception.*;
import com.ambow.store.controller.util.Result;
import com.ambow.store.service.exception.*;
import org.springframework.web.bind.annotation.ExceptionHandler;
import javax.servlet.http.HttpSession;

public class BaseController {

    public static final int OK = 200;

    //请求处理方法，这个方法的返回值就是需要传递给前端的数据
    //自动将异常对象传递给此方法的参数列表上
    //当前项目中产生了异常，被统一拦截到此方法中，这个方法此时就充当的时请求处理方法，方法的返回值直接给到前端
    @ExceptionHandler({ServiceException.class,FileUploadException.class})//用于统一处理ServiceException中抛出的异常
    public Result handleException(Throwable throwable){
        Result result = new Result(throwable);
        if (throwable instanceof UserNameRepeatException){
            result.setState(4000);
            result.setMessage("用户名已经被占用");
        }else if (throwable instanceof InsertException){
            result.setState(4001);
            result.setMessage("注册时产生未知异常");
        }else if (throwable instanceof ProductTypeException){
            result.setState(4002);
            result.setMessage("展示商品详情时产生未知异常");
        } else if (throwable instanceof FileEmptyException) {
            result.setState(5000);
            result.setMessage("上传的文件为空");
        } else if (throwable instanceof FileSizeException) {
            result.setState(5001);
            result.setMessage("上传的文件的大小超出了限制值");
        } else if (throwable instanceof FileTypeException) {
            result.setState(5002);
            result.setMessage("上传的文件类型超出了限制");
        } else if (throwable instanceof FileStateException) {
            result.setState(5003);
            result.setMessage("上传的文件状态异常");
        } else if (throwable instanceof FileUploadIOException) {
            result.setState(5004);
            result.setMessage("上传文件时读写异常");
        }else if (throwable instanceof AddressTypeException) {
            result.setState(6001);
            result.setMessage("地址功能异常");
        }else if (throwable instanceof CartTypeException) {
            result.setState(6002);
            result.setMessage("添加购物车功能异常");
        }
        return result;
    }

    /**
     * 获取session对象中的uid
     * @param request session对象
     * @return 当前登录用户的uid值
     */
    public final Integer getUidFromSession(HttpSession request){
        return Integer.valueOf(request.getAttribute("uid").toString());
    }

    public final String getUserNameFromSession(HttpSession request){
        return request.getAttribute("username").toString();
    }


}
